package com.indusfo.spc.service.impl;

import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.MaterialXOMapper;
import com.indusfo.spc.mapper.MtypeXOMapper;
import com.indusfo.spc.pojo.MtypeXO;
import com.indusfo.spc.service.MtypeXOService;
import com.indusfo.spc.vo.JSONObject;
import com.indusfo.spc.vo.XCommonUtil;
import com.indusfo.spc.vo.XTreeNode;
import com.indusfo.spc.vo.XTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: IEIS2-COM
 * @Package: com.indusfo.spc.service.impl
 * @ClassName: MtypeXOServiceImpl
 * @Author: 熊冰
 * @Description: 物料类型 业务层
 * @Date: 2019/8/21 9:59
 * @Version: 1.0
 */
@Service
public class MtypeXOServiceImpl implements MtypeXOService {



    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(MtypeXOServiceImpl.class);

    @Autowired
    private MtypeXOMapper mtypeXOMapper;

    @Autowired
    private MaterialXOMapper materialXOMapper;
    @Override
    public JSONObject listMtypeXO(MtypeXO mtypeXO) {
        try {


            // 获取一页显示多少行
            Integer pagesize = mtypeXO.getPagesize();
            // 获取查询第几页
            Integer pageindex = mtypeXO.getPageindex();

            //初始值


            // 若不为空计算从第几条开始查询
            if (pagesize != null && pageindex != null) {
                mtypeXO.setIncept(pagesize * (pageindex - 1));
            }
            // 为空进行多条的分页查询
            // 调用Mapper分页查询方法

            List<MtypeXO> listForPage = mtypeXOMapper.selectAllMtypeXO(mtypeXO);
            // 判断是否查询到数据
            if (listForPage.isEmpty()) {
                return JSONObject.oK("没有查询到相关数据",listForPage, 0);
            }
            // 查询有多少条数据条数
            if (pagesize != null && pageindex != null) {
                Integer count = mtypeXOMapper.countMtypeXO(mtypeXO);
                return JSONObject.oK(listForPage, count);
            }
            return JSONObject.oK(listForPage.get(0));



        } catch (GlobalException e) {
            // 捕获异常,打印并返回数
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }

    //新增
    @Override
    public JSONObject insertOrUpdateMtypeXO(MtypeXO mtypeXO) {
        try{
            //判断其是否存在父ID
            if(mtypeXO.getMtypePid()==null){
                mtypeXO.setMtypePid(0);
            }
            if(mtypeXO.getDataState()==null){
                mtypeXO.setDataState(1);
            }
            /**
             * @author: louk
             * @param:
             * @Return:
             * @Description: :检查物料类型名称长度以及
             * @date: 2019/9/6 9:53
             *
             */
            checkElement(mtypeXO);
            JSONObject checkParamsNotRepeatJson = checkParamsNotRepeat(mtypeXO);
            if (checkParamsNotRepeatJson.isOk()) {

                if (mtypeXO.getMtypeId()!=null) {// 有id,做更新
                    validate(mtypeXO);
                    Integer row = mtypeXOMapper.updateByPrimaryKeySelective(mtypeXO);
                    if(row == 0) {
                        throw new ModifyFailedException("更新物料类型失败！");
                    }
                    return JSONObject.oK("更新成功！", row);
                }else {// 没id,做新增
                    // 校验传入参数
                    validate(mtypeXO);
                    Integer row = mtypeXOMapper.insertSelective(mtypeXO);
                    if(row == 0) {
                        throw new ModifyFailedException("新增物料类型失败！");
                    }
                    List<MtypeXO> mtypeXOS = mtypeXOMapper.selectAllMtypeXO(mtypeXO);
                    Integer mtypeId=row;
                    if(mtypeXOS!=null && mtypeXOS.size()>0){
                        mtypeId = mtypeXOS.get(0).getMtypeId();
                    }
                    return JSONObject.oK("新增成功！", mtypeId);
                }

            }else {
                throw new ParamsErrorException(checkParamsNotRepeatJson.getMsg());
            }


        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }

    //删除
    @Override
    public JSONObject deleteMtypeXO(Long[] deteMtypeXO, Integer lDataState) {
        try {
            //1.校验
            if(deteMtypeXO == null) {
                throw new ParamsErrorException("物料类型id不能为空");
            }
            if(lDataState == null) {
                throw new ParamsErrorException("物料类型状态不能为空");
            }
            int flag = mtypeXOMapper.countBymtypePids(deteMtypeXO);
            if(flag>0){
                throw new ParamsErrorException("该物料类下扔包含子类");
            }
            int countMaterial = materialXOMapper.ListMaterialByMtype(deteMtypeXO);
            if(countMaterial>0){
                throw new ParamsErrorException("该物料类下包含物料信息无法删除");
            }
            int row = mtypeXOMapper.deleteMtypeXO(deteMtypeXO,lDataState);
            String msg = "";
            switch (lDataState) {
                case 1:
                    msg = "启用";
                    break;
                case 2:
                    msg = "删除";
                    break;
                case 3:
                    msg = "停用";
            }

            if (row == 0) {
                // 判断传入的数据状态参数lDataState,返回相应信息
                switch (lDataState) {
                    case 1:
                        throw new ModifyFailedException(msg+"失败!");
                    case 2:
                        throw new ModifyFailedException(msg+"失败!");
                    case 3:
                        throw new ModifyFailedException(msg+"失败!");
                }
            }
            Integer row1 = materialXOMapper.deleteBymtypePids(deteMtypeXO);

            return JSONObject.oK(msg+"成功！", row);
        }catch (GlobalException e){
            logger.error(e.getMessage());
            return JSONObject.build(500, e.getMessage());
        }
    }
    //树
    @Override
    public JSONObject treeMtypeXO(MtypeXO mtypeXO) {
        List<XTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<XTreeNode> nodes = new ArrayList<>();
            //获取所有的物料类别进行构建树
            List<MtypeXO> list = mtypeXOMapper.selectAllMtypeXO(mtypeXO);
            //构建一个标志,当其不为空的时候树上增加全部
            if(mtypeXO.getFlag()!=null){
                XTreeNode node0=new XTreeNode();
                MtypeXO mx=new MtypeXO();
                mx.setMtypeId(0);
                mx.setMtypePid(0);
                mx.setMtypeName("全部");
                node0.setId(mx.getMtypeId());
                node0.setpId(mx.getMtypePid() == 0 ? null : mx.getMtypePid());
                node0.setOpen(true);
                node0.setTitle(mx.getMtypeName());
                list.add(0,mx);
            }
            //当标志大于0的时候,将其父的expand改为true,该树改为的selected改为true
            if (null != list) {
                for (MtypeXO _MouldType : list) {
                    XTreeNode node = new XTreeNode();
                    node.setId(_MouldType.getMtypeId());
                    node.setpId(_MouldType.getMtypePid() == 0 ? null : _MouldType.getMtypePid());
                    node.setOpen(true);
                    node.setTitle(_MouldType.getMtypeName());
                    nodes.add(node);
                }
            }
            if(mtypeXO.getFlag()!=null && mtypeXO.getFlag()>0){
                if(mtypeXO.getFlag()>0){
                    List<XTreeNode> aBoolean = new XTreeUtil().getBoolean(mtypeXO.getFlag(), nodes);
                    //当页面初始化的时候为树的第一个默认是点亮的状态
                    tree = XCommonUtil.getTree(aBoolean, null);
                    return JSONObject.oK(tree);
                }
            }else{
                //当页面初始化的时候为树的第一个默认是点亮的状态
                tree = XCommonUtil.getTree(nodes, null);
                tree.get(1).setSelected(true);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }

    /*//树
    @Override
    public JSONObject treeMtypeXO(MtypeXO mtypeXO) {
        List<ZTreeNode> tree = null;
        try {
            tree = new ArrayList<>();
            List<ZTreeNode> nodes = new ArrayList<>();
            List<MtypeXO> list = mtypeXOMapper.selectAllMtypeXO(mtypeXO);
            if (null != list) {
                for (MtypeXO _MouldType : list) {
                    ZTreeNode node = new ZTreeNode();
                    node.setId(_MouldType.getMtypeId());
                    node.setPId(_MouldType.getMtypePid() == 0 ? null : _MouldType.getMtypePid());
                    node.setOpen(true);
                    node.setTitle(_MouldType.getMtypeName());
                    nodes.add(node);
                }
            }
            tree = CommonUtil.getTree(nodes, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JSONObject.oK(tree);
    }*/


    //验证重复
    private JSONObject checkParamsNotRepeat(MtypeXO mtypeXO) {
        try {
            // 判断不良原因类型ID是否传入


            MtypeXO check = new MtypeXO();
            check.setMtypeName(mtypeXO.getMtypeName());
            if (mtypeXO.getMtypeId() != null) {
                // 有SOP基础资料ID为更新操作,调用剔除本条记录是否有重复
                check.setMtypeId(mtypeXO.getMtypeId());
                int row = mtypeXOMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品!");
                }
            } else {

                int row = mtypeXOMapper.countParamsNotRepeat(check);
                if (row > 0) {
                    throw new ParamsErrorException("已存在该产品!");
                }
            }
            return JSONObject.oK();

        } catch (GlobalException e) {
            // 捕获异常,打印并返回
            logger.error(e.getMessage(), e);
            return JSONObject.build(500, e.getMessage());
        }
    }


    //非空判断
    private void validate(MtypeXO mtypeXO) {
        //类型名称
        String mtypeXOName =mtypeXO.getMtypeName();

        if(StringUtils.isEmpty(mtypeXOName)){
            throw new ParamsErrorException("类型名称不能为空");
        }
    }
    private  void checkElement(MtypeXO mtypeXO){
        if(StringUtils.isEmpty(mtypeXO.getMtypeName())){
            throw new ParamsErrorException("物料类别名称不能为空");
        }
        if(mtypeXO.getMtypeName().length()>50){
            throw new ParamsErrorException("物料类别名称不能大于50");
        }
    }
}
